import { Directive } from 'vue'

// 1 创建一个被观察对象的集合
const map = new WeakMap()

// 2 创建一个响应式的元素观察器：当变化时执行回调
const ob = new ResizeObserver((entries) => {
    // console.log('ResizeObserver', entries)
    for (const entry of entries) {
        // console.log('entry', entry)
        const handler = map.get(entry.target)
        handler?.({
            width: entry.borderBoxSize[0].inlineSize,
            height: entry.borderBoxSize[0].blockSize,
        })
    }
})

/**
 * @ClassName resize
 * @Description resize指令：窗口大小变化监听
 * @Author xuyizhuo
 * @Date 2024/5/24 12:26
 */
const resize: Directive = {
    // 3 元素挂载完成：（1）绑定观察的对象；（2）存储观察的元素
    mounted(el, binding) {
        //console.log('mounted el, binding', el, binding)
        //console.log('binding.value', binding.value)
        ob.observe(el)
        map.set(el, binding.value)
    },
    // 4 元素卸载完成：（1）移除观察的对象；（2）被观察的列表中移除元素
    unmounted(el) {
        // console.log('unmounted el', el)
        ob.unobserve(el)
        map.delete(el)
    },
}

export default resize
